/**
 * 滚动感知的悬浮提示框控制器
 * @param {string} elementId - 需要控制的元素ID
 * @param {number} offsetTop - 距离视口顶部的偏移量(px)
 * @returns {{ destroy: Function }} 控制器方法
 */
export function setupScrollAwareTooltip(elementId, offsetTop) {
  const tooltip = document.getElementById(elementId)
  if (!tooltip) {
    console.warn(`未找到ID为"${elementId}"的元素`)
    return null
  }

  let windowHeight = window.innerHeight
  let debounceTimer = null

  // 设置初始样式
  tooltip.style.position = 'fixed'
  tooltip.style.top = `${offsetTop}px`
  tooltip.style.left = '250px'
  tooltip.style.transition = 'opacity 0.3s ease'

  const checkVisibility = () => {
    const scrollY = window.scrollY || window.pageYOffset
    tooltip.style.opacity = scrollY < windowHeight ? '1' : '0'
  }

  const debouncedCheck = () => {
    clearTimeout(debounceTimer)
    debounceTimer = setTimeout(checkVisibility, 50)
  }

  const handleResize = () => {
    windowHeight = window.innerHeight
    debouncedCheck()
  }

  window.addEventListener('resize', handleResize)
  window.addEventListener('scroll', debouncedCheck)

  // 初始检查
  checkVisibility()

  return {
    destroy() {
      window.removeEventListener('resize', handleResize)
      window.removeEventListener('scroll', debouncedCheck)
      clearTimeout(debounceTimer)
      tooltip.style.position = ''
      tooltip.style.top = ''
      tooltip.style.right = ''
      tooltip.style.transition = ''
      tooltip.style.opacity = ''
    },
  }
}

// 默认导出（可选）
export default setupScrollAwareTooltip
